<template>
    <div>
        <h1>订单统计</h1>
        <div class="date-picker">
            <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                end-placeholder="结束日期" value-format="YYYY-MM-DD HH:mm:ss" @change="fetchOrderData" />
        </div>
        <div ref="chartRef" style="width: 100%; height: 500px;"></div>
    </div>
</template>

<script setup>
import * as echarts from 'echarts';
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { getOrderTotal } from '@/api/order'; 
import dayjs from 'dayjs';

const chartRef = ref(null);
let myChart = null;
const dateRange = ref([]);
const orderData = ref([]);

// 初始化默认日期范围（最近7天）
const initDateRange = () => {
    const end = new Date();
    const start = new Date();
    start.setDate(start.getDate() - 7);
    dateRange.value = [
        dayjs(start).format('YYYY-MM-DD 00:00:00'),
        dayjs(end).format('YYYY-MM-DD 23:59:59')
    ];
};

// 获取订单数据
const fetchOrderData = async () => {
    if (!dateRange.value || dateRange.value.length !== 2) return;

    try {
        const params = {
            date: JSON.stringify([
                dayjs(dateRange.value[0]).format('YYYY-MM-DD 00:00:00'),
                dayjs(dateRange.value[1]).format('YYYY-MM-DD 23:59:59')
            ])
        };

        const res = await getOrderTotal(params);
        orderData.value = res.data || [];
        updateChart();
    } catch (error) {
        console.error('获取订单数据失败:', error);
        // 这里假设 ElMessage 是 ElementPlus 的消息提示组件，确保你已经正确引入
        ElMessage.error('获取订单数据失败: ' + (error.response?.data?.message || error.message)); 
    }
};

// 处理数据，按日期分组汇总
const processData = () => {
    const dateMap = new Map();

    orderData.value.forEach(item => {
        const date = dayjs(item.orderTime).format('YYYY-MM-DD');
        const amount = item.orderAmount || 0;

        if (dateMap.has(date)) {
            dateMap.set(date, dateMap.get(date) + amount);
        } else {
            dateMap.set(date, amount);
        }
    });

    // 填充日期范围内的所有日期
    const startDate = dayjs(dateRange.value[0]);
    const endDate = dayjs(dateRange.value[1]);
    const days = endDate.diff(startDate, 'day') + 1;

    for (let i = 0; i < days; i++) {
        const currentDate = startDate.add(i, 'day').format('YYYY-MM-DD');
        if (!dateMap.has(currentDate)) {
            dateMap.set(currentDate, 0);
        }
    }

    // 按日期排序
    const sortedDates = Array.from(dateMap.keys()).sort((a, b) => {
        return new Date(a) - new Date(b);
    });

    return {
        dates: sortedDates,
        amounts: sortedDates.map(date => dateMap.get(date))
    };
};

// 更新图表
const updateChart = () => {
    if (!myChart) return;

    const { dates, amounts } = processData();

    const option = {
        title: {
            text: '订单金额统计'
        },
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['订单金额']
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        toolbox: {
            feature: {
                saveAsImage: {
                    title:'保存为图片'
                }
            }
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: dates
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                name: '订单金额',
                type: 'line',
                stack: 'Total',
                data: amounts
            }
        ]
    };

    myChart.setOption(option);
};

// 初始化图表
const initChart = () => {
    if (chartRef.value) {
        myChart = echarts.init(chartRef.value);
        window.addEventListener('resize', handleResize);
    }
};

const handleResize = () => {
    if (myChart) {
        myChart.resize();
    }
};

onMounted(() => {
    initChart();
    initDateRange();
    fetchOrderData();
});

onBeforeUnmount(() => {
    if (myChart) {
        window.removeEventListener('resize', handleResize);
        myChart.dispose();
        myChart = null;
    }
});
</script>

<style scoped>
.date-picker {
    margin-bottom: 20px;
}

h1 {
    margin-bottom: 20px;
    font-size: 24px;
    color: #333;
}
</style>    